﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.WeChat.Services;
using NewRetail.Application.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace NewRetail.Application.Components.WeChat
{
    public class MessageHandlerMiddlewareAsync
    {
        #region params
        private readonly ILogger _logger;
        private readonly RequestDelegate _next;
        private readonly IWeChatNotifyService _weChatNotifyService;
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="next"></param>
        public MessageHandlerMiddlewareAsync(RequestDelegate next, IWeChatNotifyService weChatNotifyService, ILogger<MessageHandlerMiddlewareAsync> logger)
        {
            _next = next;
            _weChatNotifyService = weChatNotifyService;
            _logger = logger;
        }

        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            // 过滤，只有微信消息通知
            try
            {
                if (context.Request.Path.Value.Contains("/api/new-retail/wechat-notify/a-") && context.Request.Method.ToLower().Contains("post"))
                {
                    await _next(context);

                    var appId = context.Request.RouteValues["appId"].ToString();
                    //try
                    //{
                    context.Response.ContentType = "text/plain";
                    HttpRequest request = context.Request;

                    IDictionary<string, string> parameters = null;
                    var queryString = request.QueryString;
                    parameters = UtilsHelper.GetQueryParameters(queryString);
                    string signature = parameters["signature"].ToString();
                    string timestamp = parameters["timestamp"].ToString();
                    string nonce = parameters["nonce"].ToString();
                    var checkResult = _weChatNotifyService.Check(signature, timestamp, nonce, appId);
                    if (!checkResult)
                        await context.Response.WriteAsync("签名检验异常!");
                    else
                    {
                        using var reader = new StreamReader(context.Request.Body, Encoding.UTF8);
                        string content = await reader.ReadToEndAsync();
                        //响应结果
                        var responseMsg = await _weChatNotifyService.WxResponseMessage(content, appId);
                        //string responseMsg = _weChatNotifyService.WxResponse(request);
                        context.Response.Clear();
                        context.Response.ContentType = "UTF-8";
                        await context.Response.WriteAsync(responseMsg);
                    }
                    //}
                    //catch (Exception e)
                    //{
                    //    _logger.LogError(e.Message);
                    //    await context.Response.WriteAsync(e.Message);
                    //}
                }
                else
                {
                    await _next(context);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(message: e.Message, exception: e);
                await context.Response.WriteAsync(e.Message);
            }
        }
    }
}
